package com.wang.mvchain.system.service.implay;

import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wang.mvchain.common.service.BaseServiceImplay;
import com.wang.mvchain.common.util.ConstatFinalUtil;
import com.wang.mvchain.common.util.PageInfoUtil;
import com.wang.mvchain.outer.service.ITradeService;
import com.wang.mvchain.outer.util.TradeUtil;
import com.wang.mvchain.system.dao.IACoinrateDAO;
import com.wang.mvchain.system.dao.IADeptDAO;
import com.wang.mvchain.system.dao.IATradeTypeDAO;
import com.wang.mvchain.system.dao.IAWebsiteDAO;
import com.wang.mvchain.system.pojo.ACoinrate;
import com.wang.mvchain.system.pojo.ACoinrateEnum;
import com.wang.mvchain.system.pojo.ADept;
import com.wang.mvchain.system.pojo.ATradeType;
import com.wang.mvchain.system.pojo.AWebsite;
import com.wang.mvchain.system.pojo.AWebsiteEnum;
import com.wang.mvchain.system.service.IWebsiteService;
import com.wang.mvchain.users.pojo.AUsersAccount;
import com.wang.mvchain.users.service.IUsersService;

@Component("websiteService")
public class WebsiteServiceImplay extends BaseServiceImplay implements
		IWebsiteService
{

	@Resource
	private IAWebsiteDAO websiteDAO;
	@Resource
	private IACoinrateDAO coinrateDAO;
	@Resource
	private IADeptDAO deptDAO;
	@Resource
	private IATradeTypeDAO tradeTypeDAO;
	
	@Resource
	private IUsersService usersService;

	/*-----网站详情开始-----*/
	/**
	 * 添加一个网站详情
	 */
	@Override
	public JSONObject saveOneWebsiteService(AWebsite website)
	{
		JSONObject resultJSON = new JSONObject();
		int res = this.websiteDAO.save(website);
		if (res > 0)
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "添加成功");
		} else
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "添加失败");
		}
		return resultJSON;
	}

	/**
	 * 更新一个网站详情
	 */
	@Override
	public JSONObject updateOneWebsiteService(AWebsite website)
	{
		JSONObject resultJSON = new JSONObject();
		int res =  this.websiteDAO.update(website);
		if (res > 0)
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "更新成功");
		} else
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "更新失败");
		}
		return resultJSON;
	}

	/**
	 * 删除一个网站详情
	 */
	@Override
	public JSONObject deleteOneWebsiteService(AWebsite website)
	{
		JSONObject resultJSON = new JSONObject();
		int res =  this.websiteDAO.delete(website);
		if (res > 0)
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "删除成功");
		} else
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "删除失败");
		}
		return resultJSON;
	}

	/**
	 * 查询一个记录
	 */
	@Override
	public AWebsite findOneWebsiteService(Map<String, Object> condMap)
	{
		return this.websiteDAO.findOne(condMap);
	}

	/**
	 * 查询多个网站详情
	 */
	@Override
	public List<AWebsite> findCondListWebsiteService(PageInfoUtil pageInfoUtil , Map<String, Object> condMap)
	{
		List<AWebsite> websiteList = Collections.EMPTY_LIST ; 
		if(pageInfoUtil != null)
		{
			PageHelper.startPage(pageInfoUtil.getCurrentPage(), pageInfoUtil.getPageSize());
			websiteList = this.websiteDAO.findList(condMap);
			PageInfo<AWebsite> pageInfo = new PageInfo<AWebsite>(websiteList);
			websiteList = pageInfo.getList() ;
			//设置总记录数
			pageInfoUtil.setTotalRecord(Long.valueOf(pageInfo.getTotal()).intValue());
		}else
		{
			websiteList = this.websiteDAO.findList(condMap);
		}
		return websiteList;
	}

	/* ----------网站详情结束----------- */
	
	/*-----币种开始-----*/
	/**
	 * 添加一个币种
	 */
	@Override
	public JSONObject saveOneCoinrateService(ACoinrate coinrate)
	{
		JSONObject resultJSON = new JSONObject();
		int res = this.coinrateDAO.save(coinrate);
		if (res > 0)
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "添加成功");
		} else
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "添加失败");
		}
		return resultJSON;
	}

	/**
	 * 更新一个币种
	 */
	@Override
	public JSONObject updateOneCoinrateService(ACoinrate coinrate)
	{
		JSONObject resultJSON = new JSONObject();
		int res =  this.coinrateDAO.update(coinrate);
		if (res > 0)
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "更新成功");
		} else
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "更新失败");
		}
		return resultJSON;
	}

	/**
	 * 删除一个币种
	 */
	@Override
	public JSONObject deleteOneCoinrateService(ACoinrate coinrate)
	{
		JSONObject resultJSON = new JSONObject();
		int res =  this.coinrateDAO.delete(coinrate);
		if (res > 0)
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "删除成功");
		} else
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "删除失败");
		}
		return resultJSON;
	}

	/**
	 * 查询一个记录
	 */
	@Override
	public ACoinrate findOneCoinrateService(Map<String, Object> condMap)
	{
		return this.coinrateDAO.findOne(condMap);
	}

	/**
	 * 查询多个币种
	 */
	@Override
	public List<ACoinrate> findCondListCoinrateService(PageInfoUtil pageInfoUtil , Map<String, Object> condMap)
	{
		List<ACoinrate> coinrateList = Collections.EMPTY_LIST ; 
		if(pageInfoUtil != null)
		{
			//分页查询记录
			PageHelper.startPage(pageInfoUtil.getCurrentPage(), pageInfoUtil.getPageSize());
			coinrateList = this.coinrateDAO.findList(condMap);
			PageInfo<ACoinrate> pageInfo = new PageInfo<ACoinrate>(coinrateList);
			coinrateList = pageInfo.getList() ; 
			//设置总记录数
			pageInfoUtil.setTotalRecord(Long.valueOf(pageInfo.getTotal()).intValue());
		}else
		{
			//查询全部记录
			coinrateList = this.coinrateDAO.findList(condMap);
		}
		return coinrateList;
	}

	/* ----------币种结束----------- */
	
	/*-----交易类型开始-----*/
	/**
	 * 添加一个交易类型
	 */
	@Override
	public JSONObject saveOneTradeTypeService(ATradeType tradeType)
	{
		JSONObject resultJSON = new JSONObject();
		int res = this.tradeTypeDAO.save(tradeType);
		if (res > 0)
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "添加成功");
		} else
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "添加失败");
		}
		return resultJSON;
	}

	/**
	 * 更新一个交易类型
	 */
	@Override
	public JSONObject updateOneTradeTypeService(ATradeType tradeType)
	{
		JSONObject resultJSON = new JSONObject();
		int res =  this.tradeTypeDAO.update(tradeType);
		if (res > 0)
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "更新成功");
		} else
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "更新失败");
		}
		return resultJSON;
	}
	
	public JSONObject updateBatchTradeTypeService(String type,ATradeType tradeType)
	{
		JSONObject resultJSON = new JSONObject();
		int res = 0 ; 
		if("updateRate".equalsIgnoreCase(type))
		{
			res = this.tradeTypeDAO.updateRate(tradeType);
		}
		resultJSON.put("code", "0");
		resultJSON.put("info", "批量操作成功,成功条数:" + res);
		return resultJSON ; 
	}

	/**
	 * 删除一个交易类型
	 */
	@Override
	public JSONObject deleteOneTradeTypeService(ATradeType tradeType)
	{
		JSONObject resultJSON = new JSONObject();
		int res =  this.tradeTypeDAO.delete(tradeType);
		if (res > 0)
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "删除成功");
		} else
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "删除失败");
		}
		return resultJSON;
	}

	/**
	 * 查询一个记录
	 */
	@Override
	public ATradeType findOneTradeTypeService(Map<String, Object> condMap)
	{
		ATradeType tradeType =  this.tradeTypeDAO.findOne(condMap);
		return tradeType ; 
	}

	/**
	 * 查询多个交易类型
	 */
	@Override
	public List<ATradeType> findCondListTradeTypeService(PageInfoUtil pageInfoUtil , Map<String, Object> condMap)
	{
		List<ATradeType> tradeTypeList = Collections.emptyList() ; 
		if(pageInfoUtil != null)
		{
			//分页查询记录
			Page<ATradeType> pageInfo = PageHelper.startPage(pageInfoUtil.getCurrentPage(), pageInfoUtil.getPageSize());
			tradeTypeList = this.tradeTypeDAO.findList(condMap);
			//设置总记录数
			pageInfoUtil.setTotalRecord(Long.valueOf(pageInfo.getTotal()).intValue());
		}else
		{
			//查询全部记录
			tradeTypeList = this.tradeTypeDAO.findList(condMap);
		}
		return tradeTypeList ; 
	}

	/* ----------交易类型结束----------- */

	/* ----------市场深度----------- */
	/**
	 * 添加一个网站
	 */
	@Override
	public JSONObject saveOneDeptService(ADept dept)
	{
		int res =  this.deptDAO.save(dept);
		JSONObject resultJSON = new JSONObject();
		if (res > 0)
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "添加成功");
		} else
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "添加失败");
		}
		return resultJSON ; 
	}

	/**
	 * 更新一个网站
	 */
	@Override
	public JSONObject updateOneDeptService(ADept dept)
	{
		int res =  this.deptDAO.update(dept);
		JSONObject resultJSON = new JSONObject();
		if (res > 0)
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "更新成功");
		} else
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "更新失败");
		}
		return resultJSON ; 
	}

	/**
	 * 删除一个网站
	 */
	@Override
	public JSONObject deleteOneDeptService(ADept dept)
	{
		int res =  this.deptDAO.delete(dept);
		JSONObject resultJSON = new JSONObject();
		if (res > 0)
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "更新成功");
		} else
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "更新失败");
		}
		return resultJSON ; 
	}
	
	@Override
	public JSONObject updateBatchDeptService(String type , List<ADept> deptList)
	{
		JSONObject resultJSON = new JSONObject();
		int res = 0 ; 
		if("1".equalsIgnoreCase(type))
		{
			if(deptList.size() > 0 )
			{
				//批量增加
				res = this.deptDAO.saveBatch(deptList);
			}
		}else if("2".equalsIgnoreCase(type))
		{
			if(deptList.size() > 0 )
			{
				//批量更新
				res = this.deptDAO.updateBatch(deptList);
			}
		}
		resultJSON.put("code", "0");
		resultJSON.put("info", "批量操作成功,总条数:"+ deptList.size() +";成功条数:" + res);
		return resultJSON ; 
	}

	/**
	 * 查询一个记录
	 */
	@Override
	public ADept findOneDeptService(Map<String, Object> condMap)
	{
		ADept dept =  this.deptDAO.findOne(condMap);
		return dept ; 
	}

	/**
	 * 查询多个网站
	 */
	@Override
	public List<ADept> findCondListDeptService(PageInfoUtil pageInfoUtil , Map<String, Object> condMap)
	{
		List<ADept> deptList = Collections.emptyList() ; 
		if(pageInfoUtil != null)
		{
			Page<ADept> pageInfo = PageHelper.startPage(pageInfoUtil.getCurrentPage(), pageInfoUtil.getPageSize());
			deptList = this.deptDAO.findList(condMap);
			//设置总记录数
			pageInfoUtil.setTotalRecord(Long.valueOf(pageInfo.getTotal()).intValue());
		}else
		{
			deptList = this.deptDAO.findList(condMap);
		}
		return deptList ; 
	}
	/*-----网站结束-----*/

	@Override
	public Map<String, JSONArray> operFindCommonPairService()
	{
		int totalSize = 0 ; 
		/*
		 * 键为交易对,值为出现的数量
		 * */
		Map<String, JSONArray> tradeNumMap = new HashMap<String, JSONArray>();
		/* 查询所有启用的网站 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.clear();
		condMap.put("status", AWebsiteEnum.STATUS_ENABLE.getStatus());
		/* 查询所有启用的交易网站 */
		List<AWebsite> websiteList = this.findCondListWebsiteService(null, condMap);
		for (Iterator iterator = websiteList.iterator(); iterator.hasNext();)
		{
			AWebsite website = (AWebsite) iterator.next();
			ITradeService tradeService = TradeUtil.tradeServiceMap.get(website.getId() + "");
			/* 查询所有的交易对 */
			Map<String, String> paramsMap = new HashMap<String, String>();
			JSONObject responseJSON = tradeService.findAllTransPair(paramsMap);
			if("0".equalsIgnoreCase(responseJSON.getString("code")))
			{
				totalSize ++ ; 
				
				/* 成功 */
				JSONObject dataResJSON = (JSONObject) responseJSON.get("data");
				for (Iterator iterator2 = dataResJSON.entrySet().iterator(); iterator2.hasNext();)
				{
					Entry entry = (Entry) iterator2.next();
					/* key:交易对 */
					/* 值是map,存储了交易网站和出现的次数 */
					String key = entry.getKey() + "" ; 
					JSONObject valJSON = (JSONObject) entry.getValue() ; 
					JSONArray valArr = (JSONArray) tradeNumMap.get(key);
					if(valArr == null)
					{
						valArr = new JSONArray();
					}
					JSONObject itemsJSON = new JSONObject();
					itemsJSON.put("webId", website.getId());
					itemsJSON.put("webName", website.getName());
					
					valArr.add(itemsJSON);
					tradeNumMap.put(key, valArr);
					
					/* 更新交易网站,交易币种对应的最小交易额 */
					/* 根据交易网站和交易币种查询usersAccount */
					/* 判断一下此交易对是否在acoinrate表中 */
					String[] keys = key.split("_");
					condMap.clear();
					condMap.put("engname", keys[0]);
					ACoinrate coinrate = this.findOneCoinrateService(condMap);
					if(coinrate == null)
					{
						continue ; 
					}
					
					double min_size = valJSON.getDoubleValue("min_size");
					
					condMap.clear();
					condMap.put("coinid", coinrate.getId());
					condMap.put("wbid", website.getId());
					List<AUsersAccount> usersAccList = this.usersService.findCondListUsersAccountService(new PageInfoUtil(), condMap);
					for (Iterator iterator3 = usersAccList.iterator(); iterator3.hasNext();)
					{
						AUsersAccount usersAccount = (AUsersAccount) iterator3.next();
						/* 获取usersAccount */
						if(usersAccount.getTrademinnum() <= min_size && min_size > 0)
						{
							/* 设置最小交易量 */
							usersAccount.setTrademinnum(min_size);
							/* 设置最大交易量 */
							usersAccount.setTrademaxnum( min_size * (1 + Double.valueOf(ConstatFinalUtil.SYSPRO_MAP.get("trade.num.percent"))));
						}
						usersAccount.setUpdatetime(new Date());
						this.usersService.updateOneUsersAccountService(usersAccount);
					}
				}
			}
		}
		
		for (Iterator iterator = tradeNumMap.entrySet().iterator(); iterator.hasNext();)
		{
			Entry me = (Entry) iterator.next();
			String key = me.getKey() + "" ;
			JSONArray valArr = (JSONArray) me.getValue() ;
			
			for (Iterator iterator2 = valArr.iterator(); iterator2.hasNext();)
			{
				JSONObject itemsJSON = (JSONObject) iterator2.next();
				
				String webId = itemsJSON.get("webId") + "";
				String webName = itemsJSON.get("webName") + "";
				
				/* 进行数据库操作 */
				String[] coins = key.split("_");
				/* 判断一下此交易对是否在acoinrate表中 */
				condMap.clear();
				condMap.put("engname", coins[0]);
				ACoinrate coinrate = this.findOneCoinrateService(condMap);
				
				JSONObject websiteTempJSON = new JSONObject();
				websiteTempJSON.put("id", webId);
				websiteTempJSON.put("name", webName);
				//websiteTempJSON.put("val", valArr.size());
				
				if(coinrate != null)
				{
					if(valArr.size() < 2)
					{
						continue ; 
					}
					
					JSONObject extendJSON = coinrate.getExtendJSON() ; 
					JSONObject websiteJSON = (JSONObject) extendJSON.get("website");
					if(extendJSON.get("website") == null)
					{
						websiteJSON = new JSONObject();
					}
					
					websiteJSON.put(webId,websiteTempJSON);
					
					extendJSON.put("website", websiteJSON);
					
					coinrate.setExtend(extendJSON.toJSONString());
					coinrate.setUpdatetime(new Date());
					this.updateOneCoinrateService(coinrate);
				}else
				{
					if(valArr.size() < totalSize)
					{
						continue ; 
					}
					
					/* 木有查询到币种 */
					coinrate = new ACoinrate();
					coinrate.setName(coins[0].toUpperCase());
					coinrate.setEngname(coins[0].toUpperCase());
					coinrate.setContent(coins[0].toUpperCase());
					coinrate.setStatus(ACoinrateEnum.STATUS_ENABLE.getStatus());
					coinrate.setCreatetime(new Date());
					coinrate.setUpdatetime(new Date());
					coinrate.setPubtime(new Date());
					
					JSONObject extendJSON = new JSONObject();
					
					JSONObject websiteJSON = new JSONObject();
					websiteJSON.put(webId, websiteTempJSON);
					
					extendJSON.put("website", websiteJSON);
					coinrate.setExtend(extendJSON.toJSONString());
					this.saveOneCoinrateService(coinrate);
				}
			}
		}
		return tradeNumMap;
	}

	@Override
	public JSONObject operBatchCoinrateTradeTypeService()
	{
		/* 查询所有的币种 */
		Map<String, Object> condMap = new HashMap<String,Object>();
		
		condMap.clear();
		condMap.put("status", ACoinrateEnum.STATUS_ENABLE.getStatus());
		condMap.put("prostatus", ACoinrateEnum.PROSTATUS_ENABLE.getStatus());
		List<ACoinrate> coinrateList = this.findCondListCoinrateService(null, condMap);
		/* 循环 */
		int totalCount = coinrateList.size() ; 
		int succedCount = 0 ; 
		for (Iterator iterator = coinrateList.iterator(); iterator.hasNext();)
		{
			ACoinrate coinrate = (ACoinrate) iterator.next();
			JSONObject extendJSON = coinrate.getExtendJSON();
			JSONObject websiteJSON = (JSONObject) extendJSON.get("website");
			if(websiteJSON != null)
			{
				/* 保存交易类型 */
				String name = coinrate.getEngname() + "_usdt" ; 
				name = name.toLowerCase();
				condMap.clear();
				condMap.put("name", name);
				ATradeType tradeType = this.findOneTradeTypeService(condMap);
				if(tradeType == null)
				{
					tradeType = new ATradeType() ; 
					tradeType.setName(name);
					tradeType.setFromcoinid(coinrate.getId());
					tradeType.setTocoinid(ConstatFinalUtil.CONFIG_JSON.getIntValue("USD_ID"));
					tradeType.setContent(name);
					tradeType.setRate(1);
					tradeType.setCreatetime(new Date());
					tradeType.setUpdatetime(new Date());
					tradeType.setPubtime(new Date());
					JSONObject resDbJSON = this.saveOneTradeTypeService(tradeType);
					if("0".equalsIgnoreCase(resDbJSON.get("code") + ""))
					{
						succedCount ++ ; 
					}
				}
			}
		}
		JSONObject resultJSON = new JSONObject();
		resultJSON.put("code", "0");
		resultJSON.put("info", "添加成功,总数:" + totalCount + ",成功:" + succedCount);
		return resultJSON;
	}
	
	public JSONObject operBatchWebsiteBatchService()
	{
		/* 查询所有的币种 */
		Map<String, Object> condMap = new HashMap<String,Object>();
		
		condMap.clear();
		condMap.put("status", ACoinrateEnum.STATUS_ENABLE.getStatus());
		condMap.put("prostatus", ACoinrateEnum.PROSTATUS_ENABLE.getStatus());
		List<ACoinrate> coinrateList = this.findCondListCoinrateService(null, condMap);
		/* 循环 */
		int totalCount = coinrateList.size() ; 
		int succedCount = 0 ; 
		for (Iterator iterator = coinrateList.iterator(); iterator.hasNext();)
		{
			ACoinrate coinrate = (ACoinrate) iterator.next();
			JSONObject extendJSON = coinrate.getExtendJSON();
			JSONObject websiteJSON = (JSONObject) extendJSON.get("website");
			if(websiteJSON != null)
			{
				/* 保存交易类型 */
				String name = coinrate.getEngname() + "_usdt" ; 
				name = name.toLowerCase();
				condMap.clear();
				condMap.put("name", name);
				ATradeType tradeType = this.findOneTradeTypeService(condMap);
				if(tradeType != null)
				{
					/* 把此交易类型放到交易网站中 */
					for (Iterator iterator2 = websiteJSON.entrySet().iterator(); iterator2.hasNext();)
					{
						Entry me = (Entry)iterator2.next();
						String key = me.getKey() + "" ;
						JSONObject webJSONTemp = (JSONObject) me.getValue() ; 
						String webId = webJSONTemp.get("id") + "";
						/* 查询交易网站 */
						condMap.clear();
						condMap.put("id", webId);
						AWebsite website = this.findOneWebsiteService(condMap);
						if(website != null)
						{
							JSONObject moneyStatusJSON = website.getMoneyStatusJSON();
							JSONObject moneyResJSON = moneyStatusJSON.getJSONObject(tradeType.getId() + "");
							if(moneyResJSON == null)
							{
								/* 创建一个新的交易币种 
								 * {"19":{"tradeFee":"0","name":"omg_usdt","id":"19","status":"1"}}
								 * */
								JSONObject moneyTempJSON = new JSONObject();
								moneyTempJSON.put("id", tradeType.getId());
								moneyTempJSON.put("name", tradeType.getName());
								moneyTempJSON.put("tradeFee", "0.002");
								moneyTempJSON.put("status", "1");
								
								moneyStatusJSON.put(tradeType.getId() + "", moneyTempJSON);
								
								website.setMoneystatus(moneyStatusJSON.toJSONString());
								website.setUpdatetime(new Date());
								JSONObject resDbJSON = this.updateOneWebsiteService(website);
								if("0".equalsIgnoreCase(resDbJSON.get("code") + ""))
								{
									succedCount ++ ; 
								}
							}
						}
					}
				}
			}
		}
		JSONObject resultJSON = new JSONObject();
		resultJSON.put("code", "0");
		resultJSON.put("info", "添加成功,总数:" + totalCount + ",成功:" + succedCount);
		return resultJSON;
	}
}
